package net.koodar.forge.admin.config;

import lombok.RequiredArgsConstructor;
import net.koodar.forge.admin.service.UserService;
import net.koodar.forge.security.domain.properties.SecurityProperties;
import net.koodar.forge.security.superAdmin.SuperAdminInitializer;
import net.koodar.forge.security.serive.AppUserDetailsService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.userdetails.UserDetailsService;


/**
 * @author liyc
 */
@Configuration
@RequiredArgsConstructor
public class SecurityConfig {

	private final UserService userService;
	private final AppUserDetailsService appUserDetailsService;

	/**
	 * 自定义UserDetailsService
	 */
	@Bean
	UserDetailsService userDetailsService() {
		return appUserDetailsService;
	}

	/**
	 * 初始化超级管理员账户
	 */
	@Bean
	SuperAdminInitializer superAdminInitializer() {
		return new SuperAdminInitializer(new SecurityProperties.Initializer()) {
			@Override
			public boolean isExistsSuperAdministratorUser() {
				return userService.isExistsByUsername(getSuperAdminUsername());
			}

			@Override
			public void generateAdministratorUser() {
				userService.createAdministrator(getSuperAdminUsername(), getPassword(), SUPER_ROLE_NAME);
			}
		};
	}
}
